package cn.mjnxin.iot.connector.worker;

import cn.mjnxin.iot.base.domain.ChannelData;
import cn.mjnxin.iot.base.log.LogWorker;
import cn.mjnxin.iot.base.process.DataProcessWorker;
import cn.mjnxin.iot.base.util.CommonUtil;
import cn.mjnxin.iot.connector.handle.IChannelDataHandle;

/**
 * 网关报文剥离出业务报文进行处理后放入待发送队列交给框架编码器 
 * @author CLG 2023年10月10日
 * @version V1.0.0
 */
public class Gate2ConnectorWorker extends DataProcessWorker<ChannelData> {
    private final IChannelDataHandle         channelDataHandel;

    private static Gate2ConnectorWorker worker = null;

	//非单例模式：调用一次就初始化一次
    public static void init(int poolSize, IChannelDataHandle channelDataHandle) throws Exception {
    	worker = new Gate2ConnectorWorker(poolSize, channelDataHandle);
    }

    public static Gate2ConnectorWorker getInstance() {
    	return worker;
    }
    
    private Gate2ConnectorWorker(int poolSize, IChannelDataHandle channelDataHandle) throws Exception {
        super(poolSize, "Gate2ConnectorWorker");
        this.channelDataHandel = channelDataHandle;
		this.start();
    }

	@Override
	protected void proccess(ChannelData data) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ChannelData response = channelDataHandel.resolve(data);
                    if (response != null) {
                    	Connector2GateWorker.getInstance().add(response);
                    }
                }
                catch(Exception ex) {
        			LogWorker.error("resolve(request) Exception!", ex);
                }
                finally {
                	CommonUtil.releaseData(data);
                }
            }
        }).start();
    }
}
